﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using FrontDisplay.Clock;
using FrontDisplay.Controls;
using FrontDisplay.Music;
using FrontDisplay.NativeMethods;
using MPlayer.Common;

namespace FrontDisplay.MediaPortal
{
    public class MediaPortalPlugin : PluginBase
    {
        private HwndSource _hwndSource;
        private readonly OutlineTextBlock _currentFileControl;
        private readonly PositionControl _positionControl;
        //private Process _mediaPortalProcess;

        private MusicPlugin _music;
        private ClockPlugin _clock;

        private string _currentFile;

        protected string CurrentFile
        {
            get { return _currentFile; }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _currentFile = System.IO.Path.GetFileNameWithoutExtension(value);
                }
                else
                {
                    _currentFile = value;
                }
            }
        }

        public MediaPortalPlugin()
        {
            _currentFileControl = new OutlineTextBlock
                {
                    FontSize = 70,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(7, 0, 0, 0)
                };

            _positionControl = new PositionControl { Height = 130 };
        }

        public override string Title
        {
            get { return Def.Localization.GetString("Global.Media"); }
        }

        private void UpdateFilename(string fileName)
        {
            Navigation.Navigate(InfoPage.Instance);
            CurrentFile = fileName;
            _currentFileControl.Text = CurrentFile;

            //if (_mediaPortalProcess == null)
            //{
            //    Process[] processes = Process.GetProcesses().Where(p => p.ProcessName == "MediaPortal").ToArray();

            //    if (processes.Length >= 1)
            //    {
            //        _mediaPortalProcess = processes[0];
            //        _mediaPortalProcess.EnableRaisingEvents = true;
            //        _mediaPortalProcess.Exited += MediaPortalProcessExited;
            //    }
            //}
        }

        //private void MediaPortalProcessExited(object sender, EventArgs e)
        //{
        //    Logger.Debug("Media portal exited.");

        //    _mediaPortalProcess = null;
        //}

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case WinApi.WM_COPYDATA:
                    CopyDataStruct structure = (CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));
                    string str = Marshal.PtrToStringUni(structure.lpData);
                    UpdateFilename(str);
                    handled = true;
                    break;
                case WinApi.WM_USER:
                    int position = (int) wParam;
                    int duration = (int)lParam;

                    //TODO: send and receive start & stop events
                    if (duration > 0)
                    {
                        if (_music != null)
                        {
                            if (_music.Player.State == PlayerState.Playing)
                                _music.Player.Pause(true);
                        }
                        IsActive = true;
                        //TODO: move to OnIsActiveChanged event handler
                        _clock.IsBlink = false;
                    }
                    else
                    {
                        IsActive = false;
                        //TODO: move to OnIsActiveChanged event handler
                        _clock.IsBlink = true;
                    }

                    _positionControl.UpdateTime(position, duration);
                    break;
            }
            return IntPtr.Zero;
        }

        public override void Start()
        {
            _hwndSource = HwndSource.FromHwnd(new WindowInteropHelper(Application.Current.MainWindow).Handle);
            if (_hwndSource != null) _hwndSource.AddHook(WndProc);

            _music = MainWindow.GetPlugin<MusicPlugin>();
            _clock = MainWindow.GetPlugin<ClockPlugin>();
        }

        public override void Stop()
        {
            if (_hwndSource != null) _hwndSource.RemoveHook(WndProc);
        }

        public override Control PageControl
        {
            get { return null; }
        }

        public override UIElement TopControl
        {
            get { return _currentFileControl; }
        }

        public override UIElement BottomControl
        {
            get { return _positionControl; }
        }

        public override UIElement ParametersControl
        {
            get { return null; }
        }

        //private void OpenMediaPortal()
        //{
        //    if (_mediaPortalProcess != null) return;

        //    Process[] processes = Process.GetProcesses().Where(p => p.ProcessName == "MediaPortal").ToArray();

        //    if (processes.Length >= 1)
        //    {
        //        _mediaPortalProcess = processes[0];
        //    }
        //    else
        //    {
        //        foreach (var screen in System.Windows.Forms.Screen.AllScreens)
        //        {
        //            if (screen.Bounds.Width == 1360)
        //            {
        //                try
        //                {
        //                    _mediaPortalProcess =
        //                        Process.Start(@"C:\Program Files (x86)\Team MediaPortal\MediaPortal\MediaPortal.exe");
        //                }
        //                catch
        //                {
        //                    _mediaPortalProcess = null;
        //                }
        //            }
        //        }
        //    }
        //}

    }
}
